<template>
    <div class="detail">
        <van-sticky>
            <van-nav-bar :title="getProcessedContent(detail.masterName)" left-text="返回" left-arrow
                @click-left="$router.go(-1)" />
        </van-sticky>

        <van-swipe @change="onChange" class="my-swipe" :autoplay="3000" indicator-color="white">
            <van-swipe-item v-for="(item, index) in detail.banners" :key="index">
                <img class="w100p" :src="item" />
            </van-swipe-item>

            <template #indicator>
                <div class="custom-indicator">{{ current + 1 }}/5</div>
            </template>
        </van-swipe>

        <div class="pa15 bfff">
            <div class="f14 lh15 ovh2">
                <span class="zhi f12" style="background-color: rgb(120, 160, 209);">直降</span>
                <span class="zhi f12" style="background-color: rgb(145, 188, 111);">包邮</span>
                <span>{{ detail.masterName }}</span>
                <span>{{ detail.slaveName }}</span>
            </div>
            <div>
                <p class="f13 c797d82 mt-5">果园生态种植 皮薄香甜爽口 富含天然维C</p>
            </div>
            <div class="fcb mt-15 pb-10">
                <div class="">
                    <span class="f18 c797d82 mt-5 cc03131">￥ {{ detail.minPrice | fMoney }}</span>
                    <span class="f12 c797d82 mt-5">￥{{ detail.maxPrice | fMoney }}</span>
                </div>
                <div class="fl f12 c797d82">
                    <p>3988</p>
                    <p>人购买</p>
                </div>
            </div>
            <div class="bts">
                <van-cell center title="配送至：" label="广西壮族自治区南宁市西乡塘榕华大厦313" is-link to="" />
            </div>
            <div class="bts" style="padding: 10px 13px;">
                <span class="f12 c797d82"><van-icon name="free-postage" size="14px" color="#ee0a24" /> 包邮</span>
            </div>
        </div>

        <div class="bfff mt-10">
            <div class="fcc h45 c797d82 f12">—— 商品详情 ——</div>
            <div>
                <img class="w100p" v-for="item in detail.descPics" :src="item" alt="">
            </div>
        </div>

        <div class="bfff mt-10">
            <div class="fcc h45 c797d82 f12">—— 预定流程及须知 ——</div>
            <img class="w100p" src="https://file.sdyxmall.com/h5/v1/public/app/img/group5.b0b24d0.png" alt="">
        </div>
        <div class="context pa15 f12 bfff" style="padding-bottom: 60px; color: #a6a6a6;">
            <p class="fwb mt-10 mb-10">一、关于发货</p>
            <p class="mt-10 mb-10">个工作日内发出（周末、法定节假日需顺延）个工作日内发出（周末、法定节假日需顺延）；</p>
            <p class="fwb mt-10 mb-10">二、关于发货</p>
            <p class="mt-10 mb-10">个工作日内发出（周末、法定节假日需顺延）个工作日内发出（周末、法定节假日需顺延）；</p>
            <p class="fwb mt-10 mb-10">二、关于发货</p>
            <p class="mt-10 mb-10">个工作日内发出（周末、法定节假日需顺延）个工作日内发出（周末、法定节假日需顺延）；</p>
            <p class="fwb mt-10 mb-10">二、关于发货</p>
            <p class="mt-10 mb-10">个工作日内发出（周末、法定节假日需顺延）个工作日内发出（周末、法定节假日需顺延）；</p>
        </div>


        <van-goods-action>
            <van-goods-action-icon icon="chat-o" text="客服" dot />
            <van-goods-action-icon icon="shop-o" text="店铺" dot />
            <van-goods-action-icon icon="cart-o" text="购物车" :badge="detail.cartNum ? detail.cartNum : ''"
                @click="onOpenCart" />
            <van-goods-action-button type="warning" text="加入购物车" @click="onAddToCartClick" />
            <van-goods-action-button type="danger" text="立即购买" @click="onBuyNowClick" />
        </van-goods-action>

        <van-sku v-model="showSku" :sku="sku" :goods="goods" :quota="quota" :quota-used="quotaUsed"
            @buy-clicked="onBuyClicked" @add-cart="onAddCart" />
    </div>
</template>

<script>
import Vue from 'vue';
import { SubmitBar, NavBar, Toast, Card, Checkbox, CheckboxGroup, Sticky, SwipeCell, Dialog, Cell, CellGroup, GoodsAction, GoodsActionIcon, GoodsActionButton, Sku } from 'vant';
import request from '../../utils/request'

Vue.use(Cell);
Vue.use(CellGroup);
Vue.use(SwipeCell);
Vue.use(Card);
Vue.use(NavBar);
Vue.use(SubmitBar);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Sticky);
Vue.use(GoodsAction);
Vue.use(GoodsActionIcon);
Vue.use(GoodsActionButton);
Vue.use(Sku);

export default {
    data() {
        return {
            current: 0,
            detail: {},
            showSku: false,
            sku: {
                tree: [],
                list: [],
                price: '0.00',  // 默认价格
                stock_num: 0, // 默认库存
            },
            goods: {
                picture: 'https://mall.s.maizuo.com/c8ae4728163788cda4147e1ed8c44409.png?x-oss-process=image/resize,w_180',
            },
            quotaUsed: 0,   // 限购数量
            quota: 100,     // 限购数量
        };
    },
    created() {
        let id = this.$route.params.id;
        this.detailed('http://43.136.85.99:3003/product/detail', { productId: id });
    },
    methods: {
        async detailed(url, data) {
            const res = await this.$axios.get(url, { params: data });
            this.detail = res.data.result;
            this.generateSkuData();
        },
        onChange(index) {
            this.current = index;
        },
        getProcessedContent(str) {
            const index = str.indexOf(' ');
            if (index > -1) {
                return str.slice(4, index);
            }
            return str.slice(4);
        },
        onOpenCart() {
            this.$router.push('/cart');
        },
        onAddToCartClick() {
            this.showSku = true;
        },
        onBuyNowClick() {
            this.showSku = true;
        },
        onBuyClicked(data) {
            console.log('立即购买');
            this.showSku = false;
        },
        async onAddCart(data) {
            let params = {
                productId: this.detail.productId,
                buyNum: data.selectedNum,
            }
            await request.get('/cart/add', { params })
            this.showSku = false;
            Dialog.confirm({
                message: '加入购物车成功，是否前往购物车',
                theme: 'round-button',
            }).then(() => {
                this.$router.push({
              path: '/cart',
            })
            });
        },
        generateSkuData() {
            // 从 detail 中获取商品规格列表
            const skuList = this.detail.skuList;
            // 初始化规格树
            const tree = [
                {
                    // 规格名称
                    k: '规格',
                    // 规格选项
                    v: [],
                    // 规格标识
                    k_s: 's1',
                },
            ];
            // 初始化规格列表
            const list = [];

            // 遍历商品规格列表
            skuList.forEach((item, index) => {
                // 为规格树添加规格选项
                tree[0].v.push({
                    // 规格选项 ID
                    id: String(index + 1),
                    // 规格选项名称
                    name: item.desc,
                });
                // 为规格列表添加规格记录
                list.push({
                    // 规格 ID
                    id: item.skuId,
                    // 规格价格
                    price: item.price,
                    // 对应规格选项的 ID
                    s1: String(index + 1),
                    // 规格库存，假设所有规格库存相同
                    stock_num: this.detail.inventory,
                });
            });
            // 更新商品图片
            this.goods.picture = this.detail.banners[0];
            // 更新商品规格数据
            this.sku = {
                tree,
                list,
                // 商品最低价格
                price: this.detail.minPrice.toString(),
                // 商品总库存
                stock_num: this.detail.inventory,
            };
        },
    }
}
</script>

<style scoped>
.custom-indicator {
    position: absolute;
    right: 5px;
    bottom: 5px;
    padding: 2px 5px;
    font-size: 12px;
    background: rgba(0, 0, 0, 0.1);
}

.zhi {
    height: 15px;
    line-height: 15px;
    display: inline-block;
    text-align: center;
    color: #fff;
    width: 40px;
    margin-right: 5px;
}

.bts {
    border-top: 1px solid #f2f2f2;
}
</style>